﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(5)]
public sealed class AssignLexer : BaseLexer
{
    public override bool Check()
    {
        if (Txt.Contains(' '))
        {
            if (Txt.Contains("%TYPE")) return true;
            return true;
        }
        return false;
    }

    protected override BaseCodeEntity Run()
    {
        var entity = new AssignCodeEntity();
        var txt = Txt;
        var inout = Regex.Match(txt, "\\s+(IN|OUT|INOUT)\\s+").Value;
        if (!string.IsNullOrEmpty(inout))
        {
            txt = txt.Replace(inout.Trim(), "").ReplaceSpace();
            entity.InOut = inout;
        }
        if (txt.Contains(":="))
        {
            var def = Regex.Match(txt, ":=(.*)").Result("$1").Trim();
            entity.Defult = SqlFactory.Create(def).Execute();
            txt = txt.Replace(def, "")[..^2].Trim();
        }
        var arr = txt.TrimSplit(' ');
        var type = arr[1];
        if (type.EndsWith("%TYPE")) type = OracleHelp.RealType(type);
        entity.Type = type;
        entity.Name = arr[0];
        return entity;
    }
}
